package com.yunda.yd_gis.web.controller.onlinemap;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.yunda.yd_gis.domain.YdBranch;
import com.yunda.yd_gis.domain.YdGeometry;
import com.yunda.yd_gis.domain.YdGeometryVector;
import com.yunda.yd_gis.domain.YdOrgBranch;
import com.yunda.yd_gis.service.TreenodeService;
import com.yunda.yd_gis.service.YdAddressService;
import com.yunda.yd_gis.service.YdBranchService;
import com.yunda.yd_gis.service.YdGeometryService;
import com.yunda.yd_gis.service.YdGeometryVectorService;
import com.yunda.yd_gis.service.YdOrgBranchService;
import com.yunda.yd_gis.service.YdOrgService;
import com.yunda.yd_gis.web.cache.GisCache;
import com.yunda.yd_gis.web.util.GisUtil;
import com.yunda.yd_gis.web.util.ParamUtil;
import com.yunda.yd_gis.web.util.ResourceUtil;
import com.yunda.yd_gis.web.util.ServicePoint;
import com.yunda.yd_gis.web.util.ServicePoint.MenuNode;

/**
 * @Description: ServicePointController
 * @author Linhu Li
 * @version 1.0
 * @created Dec 6, 2013
 */
@Controller
@RequestMapping("/onlinemap")
public class ServicePointController {

	@Autowired
	private TreenodeService treenodeService;
	
	@Autowired
	private YdOrgBranchService ydOrgBranchService;
	
	@Autowired
	private YdOrgService ydOrgService;
	
	@Autowired
	private YdBranchService ydBranchService;
	
    @Autowired
    private YdGeometryService ydGeoService;
    
    @Autowired
    private YdGeometryVectorService ydGeoVecService;
    
    @Autowired
    private YdAddressService ydAddressService;
	
	

	@RequestMapping("/servicePoint.do")
	public String list() {
		return "onlinemap/servicePoint";
	}

	@RequestMapping("/servicePointTree.do")
	public void getStationTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String pid = request.getParameter("id");
	    String onlyShowReleased = request.getParameter("onlyShowReleased");
	    String type=request.getParameter("type");
	    String data;
	    if(type!=null &&type.equals("branch")){
	    	data = ServicePoint.getInstance().getSonJson1(pid,!"false".equals(onlyShowReleased));
	    }else{
			data = ServicePoint.getInstance().getSonJson(pid,!"false".equals(onlyShowReleased));
		}
		response.setContentType("text/plain; charset=UTF-8");
		response.getOutputStream().write(data.getBytes("UTF-8"));
	}
	
	@ResponseBody
	@RequestMapping("/servicePointTreeAjax.do")
	public List<YdBranch> getStationData(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<YdBranch> branches = new ArrayList<YdBranch>();
		String id = request.getParameter("id");
		List<MenuNode> al = ServicePoint.getInstance().getBranchesById(id,false);
		for(MenuNode org:al) {
			YdBranch branch = GisCache.getInstance().getBranch(org.getCode());
			if(branch != null && YdBranch.State_Released.equals(branch.getState())){
				branches.add(branch);
			}
		}
		Collections.sort(branches, new Comparator<YdBranch>(){
			public  int compare(YdBranch o1, YdBranch o2){
				return o1.getYdOrg().getOrgname().compareTo(o2.getYdOrg().getOrgname());					
			}
		});
		return branches;
	}
	
	@RequestMapping("/servicePointTreeAjaxOld.do")
	public void getStationDataOld(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<YdBranch> branches = new ArrayList<YdBranch>();
		JSONObject jsonObject = new JSONObject();
		String id = request.getParameter("id");
		List<MenuNode> al = ServicePoint.getInstance().getBranchesById(id,false);
		for(MenuNode org:al) {
			YdBranch branch = GisCache.getInstance().getBranch(org.getCode());
			if(branch != null && YdBranch.State_Released.equals(branch.getState())){
				branches.add(branch);
			}
		}
		Collections.sort(branches, new Comparator<YdBranch>(){
			public  int compare(YdBranch o1, YdBranch o2){
				return o1.getYdOrg().getOrgname().compareTo(o2.getYdOrg().getOrgname());					
			}
		});
		jsonObject.put("branches",branches);
		response.setContentType("text/plain; charset=UTF-8");
		response.getOutputStream().write(jsonObject.toString().getBytes());
	}
	
	@ResponseBody
	@RequestMapping("/servicePointAutoComplete.do")
	public List<Object> servicePointAutoComplete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String keyword = request.getParameter("keyword").trim();
		List<YdBranch> orgList = new ArrayList<YdBranch>();
		List<Object> result = new ArrayList<Object>();
		if (keyword.matches("^\\d{2,6}$")) {
			orgList = ServicePoint.getInstance().getBranchOrgsByCodeStr(Integer.valueOf(keyword).toString());	
		} else {
			orgList = ServicePoint.getInstance().getBranchOrgsByNameStr(new String(keyword.getBytes("ISO-8859-1")));
		}
		if (orgList.size() > 10) {
			orgList = orgList.subList(0, 10);
		}
		for (YdBranch branch : orgList) {
			result.add(new Object() {
				private String[] data = new String[2];
				private String value;
				private Object setData(String a1, String a2) {
					data[0] = a1;
					data[1] = a2;
					value = a1;
					return this;
				}
				@SuppressWarnings("unused")
				public String[] getData() {
					return data;
				}
				@SuppressWarnings("unused")
				public String getValue() {
					return value;
				}
			}.setData(branch.getOrgcode(), branch.getYdOrg().getOrgname()));
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/servicePointKeyword.do")
	public Map<String, Object> servicePointKeyword(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String keyword = request.getParameter("keyword").trim();
		String curpage = request.getParameter("curpage");
		int page_now = 1;
		if(curpage != null && curpage !="") {
			page_now = Integer.valueOf(curpage);
		}

		List<YdBranch> list = new ArrayList<YdBranch>();
		try {
			Integer.valueOf(keyword);
			list = ServicePoint.getInstance().getBranchOrgsByCodeStr(keyword);
		} catch (NumberFormatException e) {
			list = ServicePoint.getInstance().getBranchOrgsByNameStr(keyword);
		}
		ArrayList<YdBranch> branches = new ArrayList<YdBranch>();
		ArrayList<String> branchInfos = new ArrayList<String>();
		Map<String, Object> result = new HashMap<String, Object>();
		
		Collections.sort(list, new Comparator<YdBranch>(){
			public  int compare(YdBranch branch1, YdBranch branch2){
				return branch1.getOrgcode().compareTo(branch2.getOrgcode());					
			}
		});
		
		for (int i=(page_now-1)*10;i<list.size();i++) {
			if (i >= page_now*10) {
				break;
			}
			branches.add(list.get(i));
			branchInfos.add(GisUtil.getBranchExtInfo(list.get(i).getYdOrg()));
		}
		result.put("count",list.size());
		result.put("page_now",page_now);
		result.put("branches",branches);
		result.put("branchInfos",branchInfos);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/servicePointScope.do")
	public List<YdBranch> servicePointFgfw(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return ServicePoint.getInstance().getBranchOrgsByParentCode(request.getParameter("orgcode"));
	}
	
	@RequestMapping("/branchView.do")
	public ModelAndView viewBranch(HttpServletRequest request,
			HttpServletResponse response) {
		String codeAndLevels = request.getParameter("info");
		String indexId = request.getParameter("indexid");
		String min = request.getParameter("min");
		String max = request.getParameter("max");
		String indexName = ResourceUtil.getString(indexId);
		ModelAndView model = new ModelAndView("onlinemap/branchView");
		if (codeAndLevels != null && codeAndLevels.trim().length() > 0) {
			model.addObject("codeAndLevels", codeAndLevels);
			model.addObject("indexId", indexId);
			model.addObject("min", min);
			model.addObject("max", max);
			model.addObject("indexName", indexName);
		}
		return model;
	}
	
	@ResponseBody
    @RequestMapping("/getBranchInfo.do")
	public List<Map<String,Object>> getBranchInfo(HttpServletRequest request){
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		Map<String,String> branchParam = new HashMap<String,String>();
		Map<String,String> geoParam = new HashMap<String, String>();
		String info = request.getParameter("info");
		String[] infoArray = info.split(",");
		for (int i = 0; i < infoArray.length; i ++) {
			String[] codeLevels = infoArray[i].split("-");
			String orgCode = codeLevels[0];
			String level = codeLevels[1];
			Map<String,Object> result = new HashMap<String,Object>();
			result.put("level", level);
			
			branchParam.put("orgcode", orgCode);
			YdOrgBranch orgBranch = ydOrgBranchService.getYdOrgBranch(branchParam);
			result.put("orgBranch", orgBranch);
			
			geoParam.put("businesskey", orgCode);
			Map<String,String> vectorParam = new HashMap<String,String>();
			geoParam.put("businessprop",YdGeometry.BusinessProp_Branch_ServerArea);	
			List<YdGeometry> serviceGeoList = ydGeoService.listYdGeometry(geoParam);
			if(serviceGeoList!=null){
				for(int j=0;j<serviceGeoList.size();j++){
					vectorParam.put("geometryid", serviceGeoList.get(j).getId());
					List<YdGeometryVector> serGeoVec = ydGeoVecService.listYdGeometryVector(vectorParam);
					result.put("serviceArea"+j,serGeoVec);
				}
			}
			vectorParam.put("ordercode", "1");
			geoParam.put("businessprop",YdGeometry.BusinessProp_Branch_Park);	
			List<YdGeometry> monitorGeoList = ydGeoService.listYdGeometry(geoParam);
			if(monitorGeoList!=null){
				for(int j=0;j<monitorGeoList.size();j++){
					vectorParam.put("geometryid", monitorGeoList.get(j).getId());
					YdGeometryVector monitorGeoVec = ydGeoVecService.getYdGeometryVector(vectorParam);
					result.put("monitorCircle"+j,monitorGeoVec);
				}
			}
			geoParam.put("businessprop",YdGeometry.BusinessProp_Branch_Position);
			YdGeometry positionGeo = ydGeoService.getYdGeometry(geoParam);
			if (positionGeo != null) {
				vectorParam.put("geometryid", positionGeo.getId());
				YdGeometryVector positionGeoVec = ydGeoVecService.getYdGeometryVector(vectorParam);
				result.put("position",positionGeoVec);
			}
			resultList.add(result);
		}
		return resultList;
	}
}
